//
//  YYPOAuthViewController.swift
//  weibo
//
//  Created by youyongpeng on 15/11/22.
//  Copyright © 2015年 youyongpeng. All rights reserved.
//

import UIKit

class YYPOAuthViewController: UIViewController {
    
    // 设置webView
    private lazy var webView = UIWebView()

    
    // 点击返回按钮的监听事件
    @objc private func didClickBtn() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }

    @objc private func autoFill() {
    
        
        let js = "document.getElementById('userId').value = '18234098115';" +
        "document.getElementById('passwd').value = 'yyp521';"
        
        // 让 webView 执行代码
        webView.stringByEvaluatingJavaScriptFromString(js)

    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置 view 为 webView
        view = webView

        // 设置代理
        webView.delegate = self
        
        // 添加返回按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "didClickBtn")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
        
        // 设置 webView
        self.webView.loadRequest(NSURLRequest(URL: YYPNetworkTools.sharedTools.oauthURL))
    }

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}

/// webView 的代理方法
extension YYPOAuthViewController: UIWebViewDelegate {

    
    /// 将要加载请求的代理方法
    ///
    /// - parameter webView:        webView
    /// - parameter request:        将要加载的请求
    /// - parameter navigationType: navigationType，页面跳转的方式
    ///
    /// - returns: 返回 false 不加载，返回 true 继续加载
    /// 如果 iOS 的代理方法中有返回 bool，通常返回 true 很正常，返回 false 不能正常工作
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        // 判断,如果要是百度就不加载
        // 判断访问的主机是否是百度
        guard let url = request.URL where url.host == "www.baidu.com" else {
        
            return true
        }
        
        // 判断从百度地址的 url 中提取 `code=` 是否存在
        guard let query = url.query where query.hasPrefix("code=") else {
        
            print("取消授权")
            
            return false
        }
        
        // 从 query 取出 'code=' 后面的代码
        let code = query.substringFromIndex("code=".endIndex)

        UserAccountViewModel.sharedAccoint.loadUserToken(code) { (isSuccessde) -> () in
            
            if isSuccessde {
                
                print("成功了")
                
                print(UserAccountViewModel.sharedAccoint.account)
            } else {
                
                print("失败了")
            }
            
            
        }
        
        return false
    }
    
}
